package com.wwy.listeners;

import com.wwy.model.Message;
import jakarta.annotation.Resource;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MessageListener {
    @Resource
    private JavaMailSender mailSender;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("wwy.queue.email"),
            exchange = @Exchange("wwy.exchange.direct"),
            key = {"email","all"}
    ))
    public void emailHandler(Message message){
        log.info("正在发送邮件...");
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper;
        try{
            mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
            // 配置邮件信息
            mimeMessageHelper.setFrom(message.getFrom());
            mimeMessageHelper.setTo(message.getTo());
            mimeMessageHelper.setSubject(message.getSubject());
            mimeMessageHelper.setText(message.getContent());

            mailSender.send(mimeMessageHelper.getMimeMessage());
        }catch (Exception e){
            log.info("邮件发送失败",e);
        }
    }
}
